package com.atkid.boot.generator;

import com.atkid.boot.entity.Club;
import com.atkid.boot.entity.StudentInfo;
import com.atkid.boot.service.ClubService;
import com.atkid.boot.service.StudentService;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ImageGenerator {
	@Autowired
	StudentService studentService;
	@Autowired
	ClubService clubService;

	Map<Integer, String> clubMap = new HashMap<>(50);


	@PostConstruct
	public void setClubMap() {
		List<Club> list = clubService.list();
		list.forEach((club)->{
			clubMap.put(club.getId(), club.getName());
		});
	}

	// public void generateImage(String stuName, String dept, String club, String id,
	// 		HttpServletResponse response) {
	// 	// 获取源图片路径
	// 	String endPoint = "oss-cn-beijing.aliyuncs.com";
	// 	String accessKeyId = "LTAI5t76uZPmdxQA9R9hdeJ1";
	// 	String accessKeySecret = "XtDrBvgJRNSeQAyRLQX6XvE3t6vFcn";
	// 	String bucketName = "edu-kid";
	// 	// 创建OSSClient实例。
	// 	OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
	//
	// 	// 获取文件的全路径
	// 	String fullFileName = "Image/card.jpg";
	//
	// 	// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
	// 	OSSObject ossObject = ossClient.getObject(bucketName, fullFileName);
	// 	InputStream is = ossObject.getObjectContent();
	// 	// 用imageIO读取图片
	// 	Image image = null;
	// 	try {
	// 		image = ImageIO.read(is);
	// 	} catch (IOException e) {
	// 		e.printStackTrace();
	// 		System.out.println("OSS中未找到指定文件");
	// 	}
	// 	// 利用BufferedImage，将图片加载到内存中
	// 	int height = image.getHeight(null);
	// 	int width = image.getWidth(null);
	// 	BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	//
	// 	// 获取图像对象，来对图片进行处理
	// 	Graphics2D g = bufImg.createGraphics();
	//
	// 	// 设置RenderingHints(渲染提示)，以达到文字抗锯齿的功效,(key,value)形式赋值
	// 	RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
	// 			RenderingHints.VALUE_ANTIALIAS_ON);
	// 	rh.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
	// 	rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
	// 	g.setRenderingHints(rh);
	//
	// 	// 开始处理图片
	// 	g.drawImage(image, 0, 0, width, height, null);
	//
	// 	//设置颜色。
	// 	g.setColor(Color.getHSBColor(52, 3, 0));
	//
	// 	//最后一个参数用来设置字体的大小
	// 	// Font f = LoadFont.loadFont("C:\\Users\\VictoranusQ\\AppData\\Local\\Microsoft\\Windows\\Fonts\\禹卫书法行书简体优化版.ttf",60);
	// 	Font f = new Font("宋体", Font.PLAIN, 60);
	// 	g.setFont(f);
	//
	// 	g.drawString(stuName, 500, 420);
	// 	g.drawString(id, 500, 570);
	// 	g.drawString(dept, 500, 720);
	// 	g.drawString(club, 660, 870);
	// 	g.dispose();
	//
	// 	// 为了保证原质量输出，我们用ImageWriter输出图片
	// 	// 获取ImageWriter对象
	// 	Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
	// 	ImageWriter writer = writers.next();
	//
	// 	// 网络流输出
	// 	response.setContentType("image/jpeg");
	// 	response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
	// 	response.setHeader("Content-disposition",
	// 			"attachment;filename=\"" + "card.jpg" + "\"");
	// 	OutputStream os = null;
	// 	ImageOutputStream ios = null;
	// 	try {
	// 		os = response.getOutputStream();
	// 		ios = ImageIO.createImageOutputStream(os);
	// 		// 修改ImageWriteParam，原质量输出图片
	// 		ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();
	// 		imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
	// 		imageWriteParam.setCompressionQuality(1);
	// 		// 将BufferedImage转换为IIOImage,进而输出图片
	// 		IIOImage iioImage = new IIOImage(bufImg, null, null);
	// 		// 输出
	// 		writer.setOutput(ios);
	// 		writer.write(null, iioImage, imageWriteParam);
	// 	} catch (IOException e) {
	// 		e.printStackTrace();
	// 	} finally {
	// 		if (ios != null) {
	// 			try {
	// 				os.close();
	// 			} catch (IOException e) {
	// 				e.printStackTrace();
	// 			}
	// 		}
	// 		if (ios != null) {
	// 			try {
	// 				ios.close();
	// 			} catch (IOException e) {
	// 				e.printStackTrace();
	// 			}
	// 		}
	// 	}
	// 	ossClient.shutdown();
	// }


	public void generateImageToDest(String stuName, String dept, Integer clubId, String id,
			String destFilePath) {

		// 将clubId转化为clubName
		String clubName = null;
		try {
			clubName = clubMap.get(clubId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 获取图片路径（本地读取图片）
		InputStream is = null;
		Image image = null;
		try {
			/**
			 * 将文件放在该项目中，在下方填入文件路径
			 */
			is = new FileInputStream("D:\\Java\\club_registration_system\\source.jpg");
			// 用imageIO读取图片
			image = ImageIO.read(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// 利用BufferedImage，将图片加载到内存中
		int height = image.getHeight(null);
		int width = image.getWidth(null);
		BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		// 获取图像对象，来对图片进行处理
		Graphics2D g = bufImg.createGraphics();

		// 设置RenderingHints(渲染提示)，以达到文字抗锯齿的功效,(key,value)形式赋值
		RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		rh.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
		rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
		g.setRenderingHints(rh);

		// 开始处理图片
		g.drawImage(image, 0, 0, width, height, null);

		//设置颜色。
		g.setColor(Color.getHSBColor(52, 3, 0));

		//最后一个参数用来设置字体的大小
		/**
		 * 实际使用时，使用第一种字体
		 * 将宋体字体注释掉
		 */
		// Font f = LoadFont.loadFont("C:\\Users\\VictoranusQ\\AppData\\Local\\Microsoft\\Windows\\Fonts\\禹卫书法行书简体优化版.ttf",60);
		Font f = new Font("宋体", Font.PLAIN, 60);
		g.setFont(f);

		g.drawString(stuName, 500, 420);
		g.drawString(id, 500, 570);
		g.drawString(dept, 500, 720);
		g.drawString(clubName, 660, 870);
		g.dispose();

		// 为了保证原质量输出，我们用ImageWriter输出图片
		// 获取ImageWriter对象
		Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
		ImageWriter writer = writers.next();

		OutputStream os = null;
		ImageOutputStream ios = null;
		try {
			os = new FileOutputStream(destFilePath + "\\" + id + "-" + clubId + ".jpg");
			ios = ImageIO.createImageOutputStream(os);
			// 修改ImageWriteParam，原质量输出图片
			ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();
			imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			imageWriteParam.setCompressionQuality(1);
			// 将BufferedImage转换为IIOImage,进而输出图片
			IIOImage iioImage = new IIOImage(bufImg, null, null);
			// 输出
			writer.setOutput(ios);
			writer.write(null, iioImage, imageWriteParam);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ios != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (ios != null) {
				try {
					ios.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// ossClient.shutdown();
	}

	public void batchGenerateImage() {
		List<StudentInfo> studentInfos = studentService.ListSignalClubStudentInfo();
		String destPath = "C:\\Users\\DELL\\Desktop\\imgs";
		studentInfos.forEach((info) -> {
			this.generateImageToDest(info.getName(),info.getDepartment(),info.getClubId(),info.getId(),destPath);
		});
		System.out.println(studentInfos.size());
	}
}
